package com.atomlab.daycheck.ui.login;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.atomlab.daycheck.R;
import com.atomlab.daycheck.databinding.ActivityLoginBinding;
import com.atomlab.daycheck.ui.database.DatabaseActivity;
import com.huawei.agconnect.auth.AGConnectAuth;
import com.huawei.agconnect.auth.AGConnectAuthCredential;
import com.huawei.agconnect.auth.AGConnectUser;
import com.huawei.agconnect.auth.PhoneAuthProvider;
import com.huawei.agconnect.auth.PhoneUser;
import com.huawei.agconnect.auth.SignInResult;
import com.huawei.agconnect.auth.VerifyCodeResult;
import com.huawei.agconnect.auth.VerifyCodeSettings;
import com.huawei.hmf.tasks.OnFailureListener;
import com.huawei.hmf.tasks.OnSuccessListener;
import com.huawei.hmf.tasks.Task;
import com.huawei.hmf.tasks.TaskExecutors;

import java.util.Locale;

public class LoginActivity extends AppCompatActivity {

    private LoginViewModel loginViewModel;
    private ActivityLoginBinding binding;
    private String TAG = "LoginActivity:";
    private String countryCodeStr = "86";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityLoginBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        loginViewModel = new ViewModelProvider(this, new LoginViewModelFactory())
                .get(LoginViewModel.class);

        final EditText usernameEditText = binding.username;
        final EditText passwordEditText = binding.password;
        final Button loginButton = binding.login;
        final ProgressBar loadingProgressBar = binding.loading;
        final Button sendButton = binding.btnSend;

        loginViewModel.getLoginFormState().observe(this, new Observer<LoginFormState>() {
            @Override
            public void onChanged(@Nullable LoginFormState loginFormState) {
                if (loginFormState == null) {
                    return;
                }
                loginButton.setEnabled(loginFormState.isDataValid());
                if (loginFormState.getUsernameError() != null) {
                    usernameEditText.setError(getString(loginFormState.getUsernameError()));
                }
                if (loginFormState.getPasswordError() != null) {
                    passwordEditText.setError(getString(loginFormState.getPasswordError()));
                }
            }
        });

        loginViewModel.getLoginResult().observe(this, new Observer<LoginResult>() {
            @Override
            public void onChanged(@Nullable LoginResult loginResult) {
                if (loginResult == null) {
                    return;
                }
                loadingProgressBar.setVisibility(View.GONE);
                if (loginResult.getError() != null) {
                    showLoginFailed(loginResult.getError());
                }
                if (loginResult.getSuccess() != null) {
                    login(usernameEditText,passwordEditText);
                }
            }
        });


        TextWatcher afterTextChangedListener = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // ignore
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // ignore
            }

            @Override
            public void afterTextChanged(Editable s) {
                loginViewModel.loginDataChanged(usernameEditText.getText().toString(),
                        passwordEditText.getText().toString());
            }
        };
        usernameEditText.addTextChangedListener(afterTextChangedListener);
        passwordEditText.addTextChangedListener(afterTextChangedListener);
        passwordEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    loginViewModel.login(usernameEditText.getText().toString(),
                            passwordEditText.getText().toString());
                }
                return false;
            }
        });

        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadingProgressBar.setVisibility(View.VISIBLE);
                loginViewModel.login(usernameEditText.getText().toString(),
                        passwordEditText.getText().toString());
            }
        });

        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String phoneNumberStr = usernameEditText.getText().toString().trim();
                VerifyCodeSettings settings = new VerifyCodeSettings.Builder()
                        .action(VerifyCodeSettings.ACTION_REGISTER_LOGIN)
                        .sendInterval(30)
                        .locale(Locale.CHINA)
                        .build();
                Task<VerifyCodeResult> task = AGConnectAuth.getInstance().requestVerifyCode(countryCodeStr, phoneNumberStr, settings);
                task.addOnSuccessListener(TaskExecutors.uiThread(), new OnSuccessListener<VerifyCodeResult>() {
                    @Override
                    public void onSuccess(VerifyCodeResult verifyCodeResult) {
                        //验证码申请成功
                        Log.d(TAG, "onSuccess: message send successfully"+phoneNumberStr);
                        sendButton.setText("重新发送");
                        Toast.makeText(LoginActivity.this,"验证码发送成功",Toast.LENGTH_LONG).show();
                    }
                }).addOnFailureListener(TaskExecutors.uiThread(), new OnFailureListener() {
                    @Override
                    public void onFailure(Exception e) {
                        Log.e(TAG, "onSuccess: message send failed"+phoneNumberStr);
                        Toast.makeText(LoginActivity.this, "验证码发送失败:" + e, Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
        if(AGConnectAuth.getInstance().getCurrentUser() != null)
        {
            gotoDatabaseActivity(AGConnectAuth.getInstance().getCurrentUser());
        }
    }

    private void rigister(EditText usernameEditText,EditText passwordEditText)
    {
        String phoneNumberStr = usernameEditText.getText().toString().trim();
        String vericode = passwordEditText.getText().toString().trim();
        String rePsd = "";
        PhoneUser phoneUser = new PhoneUser.Builder()
                .setCountryCode(countryCodeStr)
                .setPhoneNumber(phoneNumberStr)
                .setVerifyCode(vericode)
                .setPassword(rePsd)
                .build();
        AGConnectAuth.getInstance().createUser(phoneUser)
                .addOnSuccessListener(new OnSuccessListener<SignInResult>() {
                    @Override
                    public void onSuccess(SignInResult signInResult) {
                        //创建帐号成功后，默认已登录
                        gotoDatabaseActivity(signInResult.getUser());
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(Exception e) {
                        Toast.makeText(LoginActivity.this, "register fail:" + e, Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void login(EditText usernameEditText,EditText passwordEditText)
    {
        String phoneNumberStr = usernameEditText.getText().toString().trim();
        String vericode = passwordEditText.getText().toString().trim();
        AGConnectAuthCredential credential = PhoneAuthProvider.credentialWithVerifyCode(countryCodeStr,phoneNumberStr,"",vericode);

        AGConnectAuth.getInstance().signOut();
        AGConnectAuth.getInstance().signIn(credential)
                .addOnSuccessListener(new OnSuccessListener<SignInResult>() {
                    @Override
                    public void onSuccess(SignInResult signInResult) {
                        gotoDatabaseActivity(signInResult.getUser());
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(Exception e) {
                        Toast.makeText(LoginActivity.this, "登录失败:" + e +"尝试自动注册登录", Toast.LENGTH_LONG).show();
                        rigister(usernameEditText,passwordEditText);
                    }
                });
    }

    private void gotoDatabaseActivity(AGConnectUser user)
    {
        Intent intent = new Intent();
        intent.setClass(LoginActivity.this, DatabaseActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("DisplayName", user.getPhone());
        startActivity(intent, bundle);
        Log.i(TAG, "onSuccess: login success");
        Toast.makeText(getApplicationContext(), getString(R.string.welcome) + " " + user.getPhone(), Toast.LENGTH_LONG).show();
    }

    private void updateUiWithUser(LoggedInUserView model) {
        String welcome = getString(R.string.welcome) + model.getDisplayName();
        // TODO : initiate successful logged in experience
        Toast.makeText(getApplicationContext(), welcome, Toast.LENGTH_LONG).show();
    }

    private void showLoginFailed(@StringRes Integer errorString) {
        Toast.makeText(getApplicationContext(), errorString, Toast.LENGTH_SHORT).show();
    }
}